#coding=utf8
#LightCam 处理组播数据显示
#init by hfh 20150630

import time,re,sys,traceback,threading,subprocess,pymongo,json,os
import lc_libs

if __name__ == "__main__":


	lchome=lc_libs.lc_getlchome()
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	
	today=time.strftime('%Y%m%d',time.localtime())
	os.system("mv %s %s.%s" % (logfilename,logfilename,today))
	
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()

	try:
		#初始化数据库
		db=lc_libs.lc_mongodb_operater('127.0.0.1',27017)

		db.connect()
		Conn=db.getConn()
		if Conn==None:
			print "Can not Connect to the MondbDB"
			exit(0)
		
		perf_dbname='lc_perf'
		multicast_tablename='lc_multicast'
		
		perf_db=db.useDatabase(perf_dbname)
		multicast_table=db.UseCollection(perf_db,multicast_tablename)

	except Exception:
		excinfo=traceback.format_exc()
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" 初始化数据库失败:\n"+excinfo+"\n")
		logfile.flush()
		exit(0)
		
	portlist=[]

	for line in open(confname).readlines():
		if line[0]=="#":
			continue
		lines=line.split('\t')
		portlist.append("%s_%s" % (lines[1],lines[3]))
	#print portlist
	#timelist=['08:00','08:30','09:00','09:30','10:00','10:30','11:00','11:30','12:00','12:30','13:00','13:30','14:00','14:30','15:00','15:30','16:00','16:30','17:00']
	#timelist=['16:43','16:44','16:45','16:46','16:47','16:48','16:49','16:50','16:51','16:52','16:53','16:54','16:55','16:56','16:57','16:58','16:59']

	############### init timelist ##############################
	starttime=time.mktime(time.strptime('08:30:00','%H:%M:%S'))
	endtime=time.mktime(time.strptime('17:00:00','%H:%M:%S'))
	
	thistime=starttime
	timelist=[]
	i=0
	while True:
		thistime=thistime+i
		i=30
		thistimestr=time.strftime('%H:%M:%S',time.localtime(thistime))
		timelist.append(thistimestr)
		if thistime==endtime:
			break
		else:
			time.sleep(0.01)
	
	############################################
	#timelist=['09:42','09:43','09:44']
	print timelist
	
	today=time.strftime('%Y%m%d',time.localtime())
		
	while True:
		
		now=time.strftime('%H:%M:%S',time.localtime())
		print now
		
		if now not in timelist:
			time.sleep(1)
			continue
		else:
			print "%s it is the time to run" % now
		
		if now=='08:30:00':
			print "Drop db"
			perf_db.drop_collection(multicast_tablename)
			comd="cp %s/pyweb/static/json/multicast/lc_multicast.json %s/pyweb/static/json/multicast/history/%s.json" % (lchome,lchome,today)
			popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
			today=time.strftime('%Y%m%d',time.localtime())
		
		#logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		#logfile.write("%s run \n" % logdate)
		#logfile.flush()
		
		comd="scp ywn_monitor1:/monitor/LightCam/alert/lc_multicast_* /monitor/LightCam/alert/"
		popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		while True:
			if popen.poll()==None:
				time.sleep(0.1)
				continue
			else:
				break
		
		comd="cat /monitor/LightCam/alert/lc_multicast_*"
		popen=subprocess.Popen(comd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		idata=popen.stdout.read()
		
		idict=[]
		
		for lines in idata.split('\n'):
			line=lines.split(',')
			if len(line)<6:
				continue
			#print line
			indata={'Time':now,'Name':line[1],'Value':line[6]}
			idict.append(indata)
		
		for iport in idict:
			#print iport
			db.insertDatas(multicast_table,iport)

		###########生成json文件######################
		jdata=[]
		for item in portlist:
			
			rowdata=[]
			expr={"Name":item}
			sortcont=[("Time",pymongo.ASCENDING)]
			opts=db.queryData(multicast_table,expr,sortcont,0)
			res=db.genResult(opts)
			for line in res:
				rowdata.append(float(line['Value']))
			jdata.append({'name':item,'data':rowdata})
		
		#print json.dumps(jdata)
		file=open(lchome+"/pyweb/static/json/multicast/lc_multicast.json",'w')
		file.write(json.dumps(jdata))
		file.close()
		
		file=open(lchome+"/pyweb/static/json/multicast/lc_multicast_time.json",'w')
		file.write(json.dumps(timelist))
		file.close()
		#########################################

		time.sleep(1)
